package com.CRApp.service.impl;

import com.CRApp.mapper.OrderMapper;
import com.CRApp.pojo.Order;
import com.CRApp.service.OrderService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Random;

/**
 * 订单服务实现类
 */
@Service
public class OrderServiceImpl implements OrderService {
    
    private static final Logger logger = LoggerFactory.getLogger(OrderServiceImpl.class);
    
    @Autowired
    private OrderMapper orderMapper;
    
    /**
     * 生成唯一订单编号
     * 格式：年月日时分秒+6位随机数
     */
    private String generateOrderNumber() {
        // 获取当前时间
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
        String timeStr = now.format(formatter);

        // 生成6位随机数
        Random random = new Random();
        int randomNum = random.nextInt(900000) + 100000; // 生成100000-999999之间的随机数

        return timeStr + randomNum;
    }
    
    @Override
    @Transactional
    public Order createOrder(Map<String, Object> params, Integer userId) {
        try {
            // 参数获取
            Integer addressesId = (Integer) params.get("addressesId");
            Integer productId = (Integer) params.get("productId");
            String productName = (String) params.get("productName");
            Integer quantity = (Integer) params.get("quantity");
            BigDecimal productPrice = new BigDecimal(params.get("productPrice").toString());
            String productImageUrl = (String) params.get("productImageUrl");
            String recipientName = (String) params.get("recipientName");
            String phone = (String) params.get("phone");
            String address = (String) params.get("address");
            String orderNum = (String) params.get("orderNum");
            
            // 参数校验
            if (addressesId == null || productId == null || productName == null || 
                quantity == null || productPrice == null || recipientName == null || 
                phone == null || address == null) {
                logger.error("创建订单失败：参数不完整");
                return null;
            }
            
            // 计算订单总价
            BigDecimal totalPrice = productPrice.multiply(new BigDecimal(quantity));
            
            // 创建订单对象
            Order order = new Order();
            order.setOrderNumber(generateOrderNumber());
            order.setAddressesId(addressesId);
            order.setUserId(userId);
            order.setProductId(productId);
            order.setProductName(productName);
            order.setQuantity(quantity);
            order.setProductPrice(productPrice);
            order.setTotalPrice(totalPrice);
            order.setStatus("pending"); // 默认待支付
            order.setCreatedAt(LocalDateTime.now());
            order.setRecipientName(recipientName);
            order.setPhone(phone);
            order.setAddress(address);
            order.setProductImageUrl(productImageUrl);
            
            // 保存订单
            int result = orderMapper.insert(order);
            
            if (result > 0) {
                logger.info("订单创建成功，订单编号：{}", order.getOrderNumber());
                return order;
            } else {
                logger.error("订单创建失败：数据库操作失败");
                return null;
            }
        } catch (Exception e) {
            logger.error("订单创建失败：", e);
            throw new RuntimeException("订单创建失败：" + e.getMessage());
        }
    }
    
    @Override
    @Transactional
    public List<Order> batchCreateOrders(List<Map<String, Object>> paramsList, Integer userId) {
        List<Order> orderList = new ArrayList<>();
        
        try {
            // 遍历参数列表，为每个商品创建订单
            for (Map<String, Object> params : paramsList) {
                Order order = createOrderInternal(params, userId);
                if (order != null) {
                    orderList.add(order);
                } else {
                    // 如果有一个订单创建失败，抛出异常以便回滚事务
                    throw new RuntimeException("部分订单创建失败：参数不完整");
                }
            }
            
            logger.info("批量创建订单成功，共 {} 个订单", orderList.size());
            return orderList;
        } catch (Exception e) {
            logger.error("批量创建订单失败：", e);
            throw new RuntimeException("批量创建订单失败：" + e.getMessage());
        }
    }
    
    /**
     * 内部创建订单方法，供批量创建订单使用
     * 与createOrder类似，但不抛出异常而是返回null
     */
    private Order createOrderInternal(Map<String, Object> params, Integer userId) {
        try {
            // 参数获取
            Integer addressesId = (Integer) params.get("addressesId");
            Integer productId = (Integer) params.get("productId");
            String productName = (String) params.get("productName");
            Integer quantity = (Integer) params.get("quantity");
            BigDecimal productPrice = new BigDecimal(params.get("productPrice").toString());
            String productImageUrl = (String) params.get("productImageUrl");
            String recipientName = (String) params.get("recipientName");
            String phone = (String) params.get("phone");
            String address = (String) params.get("address");
            
            // 参数校验
            if (addressesId == null || productId == null || productName == null || 
                quantity == null || productPrice == null || recipientName == null || 
                phone == null || address == null) {
                logger.error("创建订单失败：参数不完整");
                return null;
            }
            
            // 计算订单总价
            BigDecimal totalPrice = productPrice.multiply(new BigDecimal(quantity));
            
            // 创建订单对象
            Order order = new Order();
            order.setOrderNumber(generateOrderNumber());
            order.setAddressesId(addressesId);
            order.setUserId(userId);
            order.setProductId(productId);
            order.setProductName(productName);
            order.setQuantity(quantity);
            order.setProductPrice(productPrice);
            order.setTotalPrice(totalPrice);
            order.setStatus("pending"); // 默认待支付
            order.setCreatedAt(LocalDateTime.now());
            order.setRecipientName(recipientName);
            order.setPhone(phone);
            order.setAddress(address);
            order.setProductImageUrl(productImageUrl);
            
            // 保存订单
            int result = orderMapper.insert(order);
            
            if (result > 0) {
                logger.info("单个订单创建成功，订单编号：{}", order.getOrderNumber());
                return order;
            } else {
                logger.error("单个订单创建失败：数据库操作失败");
                return null;
            }
        } catch (Exception e) {
            logger.error("单个订单创建失败：", e);
            return null;
        }
    }
    
    @Override
    public List<Order> getUserOrders(Integer userId) {
        try {
            return orderMapper.findByUserId(userId);
        } catch (Exception e) {
            logger.error("获取用户订单列表失败：", e);
            return List.of();
        }
    }
    
    @Override
    public Order getOrderDetail(String orderNumber, Integer userId) {
        try {
            Order order = orderMapper.findByOrderNumber(orderNumber);
            
            // 验证订单是否存在且属于当前用户
            if (order != null && order.getUserId().equals(userId)) {
                return order;
            }
            
            logger.warn("获取订单详情失败：订单不存在或不属于当前用户");
            return null;
        } catch (Exception e) {
            logger.error("获取订单详情失败：", e);
            return null;
        }
    }
    
    @Override
    @Transactional
    public boolean updateOrderStatus(String orderNumber, String status, Integer userId) {
        try {
            Order order = orderMapper.findByOrderNumber(orderNumber);
            
            // 验证订单是否存在且属于当前用户
            if (order == null || !order.getUserId().equals(userId)) {
                logger.warn("更新订单状态失败：订单不存在或不属于当前用户");
                return false;
            }
            
            // 检查状态值是否有效
            if (!isValidStatus(status)) {
                logger.warn("更新订单状态失败：无效的状态值 - {}", status);
                return false;
            }
            
            // 更新状态
            int result = orderMapper.updateStatus(orderNumber, status);
            
            if (result > 0) {
                logger.info("订单状态更新成功，订单编号：{}, 新状态：{}", orderNumber, status);
                return true;
            } else {
                logger.error("订单状态更新失败：数据库操作失败");
                return false;
            }
        } catch (Exception e) {
            logger.error("更新订单状态失败：", e);
            return false;
        }
    }
    
    @Override
    @Transactional
    public boolean cancelOrder(String orderNumber, Integer userId) {
        try {
            Order order = orderMapper.findByOrderNumber(orderNumber);
            
            // 验证订单是否存在且属于当前用户
            if (order == null || !order.getUserId().equals(userId)) {
                logger.warn("取消订单失败：订单不存在或不属于当前用户");
                return false;
            }
            
            // 只有待支付和已支付状态可以取消
            if (!"pending".equals(order.getStatus()) && !"paid".equals(order.getStatus())) {
                logger.warn("取消订单失败：当前订单状态不允许取消 - {}", order.getStatus());
                return false;
            }
            
            // 更新状态为已取消
            int result = orderMapper.updateStatus(orderNumber, "canceled");
            
            if (result > 0) {
                logger.info("订单取消成功，订单编号：{}", orderNumber);
                return true;
            } else {
                logger.error("订单取消失败：数据库操作失败");
                return false;
            }
        } catch (Exception e) {
            logger.error("取消订单失败：", e);
            return false;
        }
    }
    
    @Override
    @Transactional
    public boolean deleteOrder(String orderNumber, Integer userId) {
        try {
            // 执行删除
            int result = orderMapper.delete(orderNumber, userId);
            
            if (result > 0) {
                logger.info("订单删除成功，订单编号：{}", orderNumber);
                return true;
            } else {
                logger.warn("订单删除失败：订单不存在或不属于当前用户");
                return false;
            }
        } catch (Exception e) {
            logger.error("删除订单失败：", e);
            return false;
        }
    }
    
    /**
     * 检查订单状态是否有效
     * @param status 状态值
     * @return 是否有效
     */
    private boolean isValidStatus(String status) {
        return "pending".equals(status) || 
               "paid".equals(status) || 
               "shipped".equals(status) || 
               "delivered".equals(status) || 
               "canceled".equals(status);
    }
} 